package com.cens.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.cens.common.to.es.SkuESModel;
import com.cens.mall.search.config.ESConfig;
import com.cens.mall.search.constant.EsConstant;
import com.cens.mall.search.service.CommoditySaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommoditySaveServiceImpl implements CommoditySaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean commodityStatusUp(List<SkuESModel> skuESModelList) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuESModel skuESModel : skuESModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.COMMODITY_INDEX);
            indexRequest.id(skuESModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuESModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ESConfig.COMMON_OPTIONS);
        //操作失败
        boolean hasFailures = bulkResponse.hasFailures();
        if(hasFailures){
            List<String> failureIds = Arrays.stream(bulkResponse.getItems())
                    .map(BulkItemResponse::getId)
                    .collect(Collectors.toList());
            log.error("商品上架失败",failureIds);
        }
        return !hasFailures;
    }
}
